// pages/car/car.js
Page({
  getCar() {
    wx.cloud.callFunction({
      name: 'getCar'
    }).then(resp => {
      this.setData({
        carList: resp.result.data
      })
      this.computed()
    })
  },
  computed() {
    const totalState = this.data.carList.every(v => v.state)
    const totalPrice = this.data.carList.filter(v => v.state).reduce((p, n) => { return p + n.count * n.price }, 0)
    this.setData({
      totalState,
      totalPrice
    })
  },
  addCount(e) {
    const _id = e.target.dataset._id;

    const carList = this.data.carList;

    const item = carList.find(v => v._id === _id);

    item.count++;

    this.setData({
      carList: carList
    })

    this.computed()
  },
  subCount(e) {
    const _id = e.target.dataset._id;

    const carList = this.data.carList;

    const item = carList.find(v => v._id === _id);

    item.count--;

    this.setData({
      carList: carList
    })

    this.computed()
  },
  changeState(e) {
    const _id = e.target.dataset._id;

    const carList = this.data.carList;

    const item = carList.find(v => v._id === _id);

    item.state = !item.state;

    this.setData({
      carList: carList
    })

    this.computed()
  },
  changeAllState(e) {
    const state = e.target.dataset.state;
    const carList = this.data.carList;
    carList.forEach(v => v.state = state);
    this.setData({
      carList: carList
    })
    this.computed()
  },
  /**
   * 页面的初始数据
   */
  data: {
    carList: [],
    totalState: true,
    totalPrice: 1000
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getCar()
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})